// pages/index/index.js
var common = require("../../common/common.js").common;

var leader = require("../../common/leader.js").leader;

var shoppingCar = require("../../common/shoppingCar.js");

var customLink = require("../../common/customLink.js");

var QQMapWX = require("../../sdk/qqmap-wx-jssdk.min.js");

var util = require("../../utils/util.js");

var un = require("../../siteinfo.js");

var event = require("../../utils/events.js");

var {$author: $author} = require("../../components/base/authorization.js");

var qqmapsdk;

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        privacyAlert: false,
        //隐私政策弹框
        alert_title: "提示",
        alert_post: "自定义海报请到商品详情页生成！",
        alert_stock: "库存不足，无法继续购买!",
        alert_success: "加入购物车成功",
        alert_error: "加入购物车失败",
        alert_mes1: "该商品是多属性商品，请到购物车操作",
        alert_shopcart: "购物车最多加99999个商品！",
        isRefresh: false,
        super_page: 1,
        super_goods: [],
        drangonList: [],
        commission_show: 0,
        num_isShow: false,
        group_list_show: 0,
        //0隐藏 1:显示
        pageWidth: "710rpx",
        //全局页面宽度
        showInfoTip: false,
        //授权失败的弹框
        leader_style: 1,
        //团长风格1顶部  2方块
        imgUrls2: [],
        current: 0,
        classfit: [],
        cart_count: 0,
        classification: 0,
        //商品上方分类是否显示 默认先隐藏
        warrant: true,
        sale_box: 0,
        //营销模块 默认不显示 根据请求开启
        page: 1,
        list: [],
        latitude: "",
        longitude: "",
        group: [],
        address: "",
        setInterval: "",
        alert: 0,
        details: [],
        price: "",
        sku: "",
        buy_count: 1,
        sku_info: "",
        style: 1,
        page2: 1,
        buylist: [],
        leader_id: "",
        leader_id2: "",
        leader_show: 3,
        chooseClass: 0,
        class: [],
        goods: [],
        color_header: "#fff",
        color_text: "white",
        color_main: "",
        color_minor: "",
        leader_change: 2,
        index_choose: 0,
        is_leader: 0,
        showLoading: 1,
        time_s: "",
        time_e: "",
        hour: "",
        minute: "",
        second: "",
        is_open: 1,
        notice: [],
        copyImg: "",
        copyText: [],
        allBottom: 0,
        //2为加载完  1为加载中  0为还有
        alert1: 0,
        alert2: 0,
        nav_fixed: "nav_normal",
        cate_fixed: "nav_normal",
        myleaderinfo: {
            leader_id: -1,
            leader_id_true: -1
        },
        notice_alert: 0,
        notice_content: "",
        sleep_img: "",
        discount: 0,
        index_discount: [],
        discount_info: [],
        discount_index: 0,
        options: "",
        s_leader: [],
        leader_id_share: "",
        kill_list: [],
        kill_now_id: "",
        //当前的秒杀时间所在tab
        kill_time: "",
        time_id: "",
        rp_name: "",
        isIPX: "",
        kill_pro: [],
        kill_hour: "",
        kill_minute: "",
        kill_second: "",
        rec_leader_tip: [],
        search_con: "",
        group_buy: [],
        showGroupbuy: 0,
        spell_goods: [],
        //拼团商品
        limit_goods: [],
        //限量商品
        img_advert: [],
        //广告图
        version: "",
        copyTitle: "",
        addShoppingCar: true,
        toastHide: true,
        leaderChange: false,
        //团长切换弹窗显示
        currentLeaderInfo: {},
        //当前团长信息
        modalHide: true,
        //提示框显示隐藏，true影藏
        tipIsShow: false,
        //右上角提示加入我的小程序显示隐藏，默认隐藏
        shoppingCarHidden: true,
        countBoxHidden: false,
        hasMore: true,
        lock_fans: 0,
        //团长强制绑定   0关  1开
        is_first: 0,
        //是否是新人 0不是  1是
        newUserProduct: [],
        animation_img: "",
        //初始加载动画
        proStyle: {
            style: 1,
            mainColor: "#47B34F"
        },
        go_back: 0,
        // 自定义头部，是否需要显示goback
        tabBar: [],
        tabBar1: [ {
            iconName: "icon-shouye1",
            tip: "首页",
            current: 1,
            num: 0,
            url: "/pages/index/index",
            openType: "switchTab"
        }, {
            iconName: "icon-fenlei1",
            tip: "分类",
            current: 0,
            num: 0,
            url: "/pages/classfit/classfit",
            openType: "switchTab"
        }, {
            iconName: "icon-gouwuche2",
            tip: "购物车",
            current: 0,
            num: 0,
            url: "/pages/shopcart/shopcart"
        }, {
            iconName: "icon-dingdan2",
            tip: "订单",
            current: 0,
            num: 0,
            url: "/pages/order/order",
            openType: "switchTab"
        }, {
            iconName: "icon-wode1",
            tip: "我的",
            current: 0,
            num: 0,
            url: "/pages/personal/personal",
            openType: "switchTab"
        } ],
        tmplIds: [],
        //模板消息tmplIds
        subscribeMessage: true,
        definePoster: false,
        features: {
            redPacket: 0,
            luckPacket: 0,
            secKill: 0,
            fullReduce: 0,
            group: 0,
            sign: 0,
            integrationExchange: 0,
            serverPro: 0,
            prepaid: 0,
            live: 0,
            specFund: 0
        },
        liveList: [],
        share_kill_time: -1,
        pro_share: false,
        awardBox: 0,
        awardList: [],
        integ: 0,
        balance: 0,
        gate_alert: 0,
        addressName: "",
        //当前城市位置
        vipStatus: 0,
        //是否为会员
        brandShow: 0,
        redPackage: [],
        //红包列表
        redPackage_id: "",
        //上一次领取红包的id
        redPackage_flag: false,
        redPackageChange: false,
        redPackageSmallFlag: false,
        index_cc: 0,
        t_cart_num: 0,
        minimum_num: 1,
        step_num: 1,
        joinCate: 1
    },
    closeAlert() {
        this.setData({
            privacyAlert: false
        });
    },
    //获取去右侧胶囊的信息
    getHeader() {
        let menuRect = wx.getMenuButtonBoundingClientRect();
        this.setData({
            topBarHeight: menuRect.height,
            topBarTop: menuRect.top,
            topBarWidth: menuRect.width
        });
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
      var page = 1;
        this.setData({
            goods: [],
            local_goods: []
        });
        var a_sale = parseInt(this.data.index_choose);
        var leader_id_true = this.data.myleaderinfo.leader_id_true ? this.data.myleaderinfo.leader_id_true : -1;
        this.getProductIndex(-1, page, a_sale, leader_id_true);
        if (wx.getPrivacySetting) {
            wx.getPrivacySetting({
                success: res => {
                    if (res.needAuthorization) {
                        this.setData({
                            privacyAlert: true
                        });
                    }
                },
                complete: res => {}
            });
        }
        this.getHeader();
        this.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        wx.showShareMenu({
            withShareTicket: false,
            menus: [ "shareAppMessage", "shareTimeline" ]
        });
        wx.hideTabBar();
        common.getAppBase().then(() => {
            qqmapsdk = new QQMapWX({
                key: that.data.appBase.location_key
            });
        });
        let that = this;
        let isIPX = app.globalData.isIPX;
        let statusBarHeight = app.globalData.statusBarHeight;
        that.setData({
            isIPX: isIPX,
            statusBarHeight: statusBarHeight
        });
        //解析分享二维码和分享首页的数据scene
                if (options && options.scene) {
            var scene = decodeURIComponent(options.scene);
            var s_leader = scene.split(":");
            that.setData({
                options: options,
                //分享内容(直接和海报)
                s_leader: s_leader,
                //分享的团长数组（海报模式，具体信息）
                s_uid: s_leader[3]
            });
        } else if (options && options.my_leaderID) {
            //团长推荐团员
            var s_leader = [];
            s_leader[0] = "s_leader";
            s_leader[1] = options.my_leaderID;
            that.setData({
                options: options,
                s_leader: s_leader
            });
        } else if (options && options.pro_id) {
            //普通商品
            if (options.time_id) {
                that.setData({
                    share_kill_time: options.time_id,
                    start_at: options.start_at,
                    pro_id: options.pro_id
                });
                that.getKillProductDetail();
            } else {
                that.setData({
                    pro_id: options.pro_id
                });
                that.getProductDetail();
            }
        } else if (options && options.uid) {
            //分销商绑定上下级
            that.setData({
                s_uid: options.uid
            });
        }
        //首次直接进入，拿openid
                if (app.globalData.user) {
            //如果直接拿到openid
            that.setData({
                openid: app.globalData.user.openid,
                uid: app.globalData.user.uid,
                is_new: app.globalData.user.is_new
            });
            leader.getMyLeaderInfo_aync(that.data.openid, that.data.s_leader[1]).then(() => {
                that.getKilltime();
                //秒杀
                                that.getSpell();
                //拼团
                                if (that.data.is_new == 0 && (!that.data.myleaderinfo.leader_id || that.data.myleaderinfo.leader_id == -1)) {
                    //定位当前位置--新用户并且无团长
                    that.setData({
                        is_new: 0
                    });
                    that.getMasterUniacid();
                    //获取主站的uniacid
                                        that.requestStart(that.data.openid);
                } else if (that.data.is_new == 1 && (!that.data.myleaderinfo.leader_id || that.data.myleaderinfo.leader_id == -1)) {
                    that.getLocationSet().then(res => {
                        if (that.data.master_auto_location == 1) {
                            //获取定位在请求基础设置
                            that.getMasterUniacid_new().then(res => {
                                that.requestStart(that.data.openid);
                            });
                        } else {
                            that.requestStart(that.data.openid);
                        }
                    });
                } else {
                    that.setData({
                        is_new: 1
                    });
                    that.requestStart(that.data.openid);
                }
            });
        } else {
            //回调拿到openid
            app.userInfoReadyCallback = (res => {
                that.setData({
                    openid: res.openid,
                    is_new: res.is_new,
                    uid: res.uid
                });
                leader.getMyLeaderInfo_aync(that.data.openid, that.data.s_leader[1]).then(() => {
                    that.getKilltime();
                    //秒杀
                                        that.getSpell();
                    //拼团
                                        if (that.data.is_new == 0 && (!that.data.myleaderinfo.leader_id || that.data.myleaderinfo.leader_id == -1)) {
                        //定位当前位置--新用户并且无团长
                        that.setData({
                            is_new: 0
                        });
                        that.getMasterUniacid();
                        //获取主站的uniacid
                                                that.requestStart(that.data.openid);
                    } else if (that.data.is_new == 1 && (!that.data.myleaderinfo.leader_id || that.data.myleaderinfo.leader_id == -1)) {
                        that.getLocationSet().then(res => {
                            if (that.data.master_auto_location == 1) {
                                //获取定位在请求基础设置
                                that.getMasterUniacid_new().then(res => {
                                    that.requestStart(that.data.openid);
                                });
                            } else {
                                that.requestStart(that.data.openid);
                            }
                        });
                    } else {
                        that.setData({
                            is_new: 1
                        });
                        that.requestStart(that.data.openid);
                    }
                });
            });
        }
        if (options && options.onshare && options.onshare == 1) {
            that.setData({
                openid: options.openid
            });
            leader.getMyLeaderInfo_aync(that.data.openid, that.data.s_leader[1]).then(() => {
                if (that.data.is_new == 0 && (!that.data.myleaderinfo.leader_id || that.data.myleaderinfo.leader_id == -1)) {
                    //定位当前位置--新用户并且无团长
                    that.setData({
                        is_new: 0
                    });
                    that.getMasterUniacid();
                    //获取主站的uniacid
                                } else {
                    that.setData({
                        is_new: 1
                    });
                }
                that.requestStart(that.data.openid);
            });
        }
        that.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        wx.getSystemInfo({
            success: function(res) {
                let rpx = res.windowWidth / 375;
                that.setData({
                    rpx: rpx
                });
            }
        });
        that.getTmplIds();
        var newPro = that.changeProInfo(that.data.goods);
        var newShoppingCart = shoppingCar.getInfo();
        that.setData({
            cart_count: wx.getStorageSync("cart_count"),
            goods: newPro,
            num_isShow: true
        });
    },
    onHide() {
        var that = this;
        that.setData({
            num_isShow: false
        });
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        let that = this;
        leader.getMyLeaderInfo(that.data.openid);
        that.getNavData();
        that.getSow();
        that.getBase();
        // var page = 1;
        // that.setData({
        //     goods: [],
        //     local_goods: []
        // });
        // var a_sale = parseInt(that.data.index_choose);
        // var leader_id_true = that.data.myleaderinfo.leader_id_true ? that.data.myleaderinfo.leader_id_true : -1;
        // that.getProductIndex(-1, page, a_sale, leader_id_true);
    },
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {
        var that = this;
        that.setData({
            num_isShow: false
        });
        //清除计时器  即清除setInter
                clearInterval(that.data.setInterval);
    },
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: common.throttle(function() {
        this.setData({
            page: 1,
            isRefresh: true
        });
        this.getIndexNewGoods(this.data.chooseClass, 1);
        this.requestStart(app.globalData.user.openid);
    }, 2e3),
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {
        let that = this;
        if (that.data.hasMore) {
            that.setData({
                hasMore: false
            });
            var chooseClass = this.data.chooseClass;
            if (this.data.chooseClass == "local2") {
                if (this.data.super_page != 1) {
                    this.getSuperGoods();
                }
            } else {
                if (this.data.page != 1) this.getIndexNewGoods(chooseClass, 1);
            }
        }
    },
    //会员卡  1,2,3会员
    getVipStatus: function() {
        let that = this;
        return new Promise(function(resolve, reject) {
            common.request({
                endpoint: "vipcard/vip-verify",
                method: "POST",
                data: "",
                success: res => {
                    var vipStatus = res.extra.vip_card;
                    vipStatus = vipStatus == 1 || vipStatus == 2 || vipStatus == 3 ? 1 : 0;
                    that.setData({
                        vipStatus: vipStatus
                    });
                    resolve();
                },
                fail(res) {
                    wx.showModal({
                        title: that.data.alert_title,
                        contnet: res.message,
                        showCancel: false
                    });
                    reject(res);
                }
            });
        });
    },
    /**
   * 分销商绑定上下级
   */
    levelShare: function() {
        let that = this;
        common.request({
            endpoint: "Level/level/level-share",
            method: "post",
            data: {
                user_id: that.data.s_uid
            },
            success: res => {
                if (that.data.level_set.success_bind_tip) {
                    wx.showToast({
                        icon: "none",
                        title: that.data.level_set.success_bind_tip
                    });
                } else {
                    wx.showToast({
                        icon: "none",
                        title: "绑定成功"
                    });
                }
            },
            fail(err) {}
        });
    },
    onShareTimeline: function() {
        let that = this;
        var my_leaderID = that.data.myleaderinfo.leader_id;
        var openid = wx.getStorageSync("user").openid;
        var buddy_img = that.data.buddy_img;
        if (buddy_img.indexOf("https:") < 0) {
            buddy_img = buddy_img.replace("http:", "https:");
        }
        return {
            title: that.data.buddy_title,
            imageUrl: buddy_img,
            // 图片 URL
            query: "onshare=1&uid=" + that.data.uid + "&openid=" + openid + "&scene=" + encodeURIComponent("s_leader:" + my_leaderID)
        };
    },
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function(e) {
        let that = this;
        if (e.target && e.target.dataset.type == "brand") {
            return {
                title: e.target.dataset.item.share_title,
                imageUrl: e.target.dataset.item.share_img,
                path: `/pages/project_active/project_active?id=${e.target.dataset.item.id}`
            };
        } else if (e.target && e.target.dataset.type == "drangon") {
            return {
                title: e.target.dataset.item.title,
                imageUrl: e.target.dataset.item.img[0],
                path: `/dragon/pages/dragonDetail/dragonDetail?id=${e.target.dataset.item.id}&leader_id_share=${that.data.myleaderinfo.leader_id}`
            };
        } else {
            var my_leaderID = that.data.myleaderinfo.leader_id ? that.data.myleaderinfo.leader_id : "0";
            var product_id = that.data.shareId;
            var share_link = that.data.share_link;
            var sharePath = that.data.sharePath;
            if (e.target && e.target.dataset.share == 2) {
                if (share_link == 1) {
                    sharePath = "/pages/shareMiddle/shareMiddle?scene=" + encodeURIComponent("l:" + my_leaderID + ":p:" + product_id + ":uid:" + that.data.uid);
                } else if (share_link == 0) {
                    sharePath = "/pages/pro_detail/pro_detail?scene=" + encodeURIComponent("l:" + my_leaderID + ":p:" + product_id + ":uid:" + that.data.uid);
                } else if (share_link == 2) {
                    sharePath = "/pages/index/index?pro_id=" + product_id + "&uid=" + that.data.uid;
                }
                return {
                    title: that.data.shareTitle,
                    imageUrl: that.data.shareCanvasPhoto,
                    path: sharePath
                };
            } else {
                var share_index = that.data.share_index;
                var share_title = that.data.share_title;
                if (my_leaderID > 0) {
                    return {
                        title: share_title,
                        imageUrl: share_index,
                        path: "/pages/index/index?scene=" + encodeURIComponent("s_leader:" + my_leaderID + ":uid:" + that.data.uid)
                    };
                } else {
                    return {
                        title: share_title,
                        imageUrl: share_index,
                        path: "/pages/index/index?scene=" + encodeURIComponent("s_leader:0" + ":uid:" + that.data.uid)
                    };
                }
            }
        }
    },
    sharetmp(e) {
        let that = this;
        wx.showLoading({
            title: "加载中"
        });
        if (that.data.share_type && that.data.share_type == 1) {
            that.shareCanvas(e);
        } else {
            that.getShareImg(e);
        }
    },
    makeWxapp_img: function(ctx, options) {
        let that = this;
        let name = that.data.title;
        let nameLen = name.length;
        let titleLen = 32.5 + nameLen * 16;
        ctx.drawImage(that.data.domain + "/img/mainPack/share_title.png", (250 - titleLen) * that.data.rpx, 0, (titleLen + 60) * that.data.rpx, 30 * that.data.rpx);
        //图片加载完成
                if (that.data.wxapp_img) {
            let wxapp_img = that.data.wxapp_img;
            if (wxapp_img.indexOf("https:") < 0) {
                wxapp_img = wxapp_img.replace("http:", "https:");
            }
            wx.getImageInfo({
                src: wxapp_img,
                success: function(res) {
                    ctx.save();
                    ctx.beginPath();
                    //开始绘
                                        ctx.arc((260 - titleLen + 35) * that.data.rpx, 15 * that.data.rpx, 10 * that.data.rpx, 0, Math.PI * 2, false);
                    ctx.clip();
                    ctx.drawImage(res.path, (260 - titleLen + 25) * that.data.rpx, 5 * that.data.rpx, 20 * that.data.rpx, 20 * that.data.rpx);
                    ctx.restore();
                    options.callback();
                },
                fail(res) {
                    options.callback();
                }
            });
        } else {
            options.callback();
        }
    },
    shareCanvas: function(e) {
        let that = this;
        let item = e.detail.item;
        const ctx = wx.createCanvasContext("shareCanvas");
        ctx.drawImage(that.data.domain + "/img/mainPack/share_bg.png", 0, 0, 300 * that.data.rpx, 240 * that.data.rpx);
        //图片加载完成时draw
                let icon_img = item.img;
        if (icon_img.indexOf("https:") < 0) {
            icon_img = icon_img.replace("http:", "https:");
        }
        wx.getImageInfo({
            src: icon_img,
            success: function(res) {
                ctx.drawImage(res.path, 60 * that.data.rpx, 10 * that.data.rpx, 175 * that.data.rpx, 175 * that.data.rpx);
                that.makeWxapp_img(ctx, {
                    callback() {
                        let name = that.data.title;
                        let nameLen = name.length;
                        let titleLen = 32.5 + nameLen * 16;
                        ctx.fillStyle = "#fff";
                        ctx.font = "normal bold 16px sans-serif";
                        ctx.fillText(name, (300 - titleLen + 15) * that.data.rpx, 20 * that.data.rpx);
                        if (that.data.sku_num_display == 1) {
                            ctx.fillStyle = "#fff";
                            ctx.font = "12px YaHei";
                            ctx.fillText("已抢" + item.order_num + "件/仅剩" + item.all_stock_num + "件", 70 * that.data.rpx, 202 * that.data.rpx);
                        }
                        ctx.fillStyle = "#fff";
                        ctx.font = "16px YaHei";
                        ctx.fillText("￥", 70 * that.data.rpx, 230 * that.data.rpx);
                        ctx.fillStyle = "#fff";
                        ctx.font = "25px YaHei";
                        ctx.fillText(item.before_price, 90 * that.data.rpx, 230 * that.data.rpx);
                        var low_price_width = ctx.measureText(item.before_price).width;
                        ctx.fillStyle = "#fff";
                        ctx.font = "16px YaHei";
                        ctx.fillText("￥" + item.original_price, (90 + low_price_width + 6) * that.data.rpx, 230 * that.data.rpx);
                        var low_oprice_width = ctx.measureText("￥" + item.original_price).width;
                        ctx.fillStyle = "#fff";
                        ctx.font = "19px YaHei";
                        ctx.fillText("社区", 8 * that.data.rpx, 210 * that.data.rpx);
                        ctx.fillText("团购", 8 * that.data.rpx, 233 * that.data.rpx);
                        ctx.fillStyle = "#fff";
                        ctx.font = "11px YaHei";
                        ctx.fillText("24小时", 255 * that.data.rpx, 220 * that.data.rpx);
                        ctx.fillText("为您服务", 248 * that.data.rpx, 234 * that.data.rpx);
                        ctx.strokeStyle = "#fff";
                        ctx.setLineWidth = 1.5 * that.data.rpx;
                        ctx.moveTo((85 + low_price_width + 6) * that.data.rpx, 225 * that.data.rpx);
                        ctx.lineTo((85 + low_price_width + 6 + low_oprice_width + 2) * that.data.rpx * that.data.rpx, 225 * that.data.rpx);
                        ctx.stroke();
                        ctx.draw(true, () => {
                            wx.canvasToTempFilePath({
                                canvasId: "shareCanvas",
                                fileType: "png",
                                success: function(res) {
                                    that.setData({
                                        shareCanvasPhoto: res.tempFilePath,
                                        shareTitle: item.title,
                                        shareId: item.id,
                                        alert2: 1
                                    });
                                },
                                fail: function(res) {
                                    that.setData({
                                        shareCanvasPhoto: item.img,
                                        shareTitle: item.title,
                                        shareId: item.id,
                                        alert2: 1
                                    });
                                },
                                complete: function(res) {
                                    wx.hideLoading();
                                }
                            }, that);
                        });
                    }
                });
            },
            fail(err) {
                wx.hideLoading();
            }
        });
    },
    makeposterGoods: function() {
        let that = this;
        var my_leaderID = that.data.myleaderinfo.leader_id;
        common.request({
            endpoint: "share/poster_read",
            method: "post",
            data: {
                lid: my_leaderID,
                id: that.data.shareId,
                uid: that.data.uid
            },
            success: res => {
                var res = JSON.parse(res);
                let poster_normal = res.data.poster_normal;
                if (poster_normal.indexOf("https") < 0) {
                    poster_normal = poster_normal.replace("http:", "https:");
                }
                if (poster_normal.indexOf("ngoods_bg") != -1) {
                    wx.navigateTo({
                        url: "/poster/pages/pro_detail_share/pro_detail_share?uid=" + that.data.uid + "&id=" + that.data.shareId
                    });
                } else {
                    //自定义
                    wx.showModal({
                        title: that.data.alert_title,
                        content: that.data.alert_post,
                        showCancel: false
                    });
                }
            }
        });
    },
    //首页分享图
    getShareImg_backstage(e) {
        let that = this;
        var item = e.detail.item;
        common.request({
            endpoint: "share/share_pro",
            method: "post",
            data: {
                id: item.id,
                //商品id
                price: item.price,
                //现价
                original_price: item.original_price,
                //原价
                sale: item.order_num,
                //已售份数
                least: Number(item.all_stock_num)
            },
            success(res) {
                if (util.compareVersion(un.version, "2.4.20") < 0) {
                    res = JSON.parse(res);
                    var imgURL = res.extra.image ? res.extra.image[0].url : "";
                    if (res.code == 4) {
                        wx.showToast({
                            title: res.extra
                        });
                        that.setData({
                            imgURL: that.data.details.icon
                        });
                    } else {
                        that.setData({
                            imgURL: imgURL
                        });
                    }
                } else {
                    var imgURL = res.extra.url ? res.extra.url : "";
                    that.setData({
                        shareId: item.id,
                        shareTitle: item.title,
                        imgURL: imgURL,
                        alert2: 1
                    });
                }
                wx.hideLoading();
            },
            fail(err) {
                that.setData({
                    shareId: item.id,
                    shareTitle: item.title,
                    imgURL: item.img,
                    alert2: 1
                });
                wx.hideLoading();
            }
        });
    },
    getShareImg: function(e) {
        let that = this;
        var item = e.detail.item;
        const ctx = wx.createCanvasContext("shareCanvas");
        let carousel = (item.img_slide ? item.img_slide[0] : "") || item.img;
        if (carousel.indexOf("https:") < 0) {
            carousel = carousel.replace("http:", "https:");
        }
        wx.getImageInfo({
            src: carousel,
            success: function(res) {
                ctx.drawImage(res.path, 0 * that.data.rpx, -60 * that.data.rpx, 300 * that.data.rpx, 300 * that.data.rpx);
                ctx.drawImage(that.data.domain + "/img/mainPack/pro_share_bg.png", 0 * that.data.rpx, 189.5 * that.data.rpx, 300 * that.data.rpx, 50.5 * that.data.rpx);
                //图片加载完成
                                ctx.fillStyle = "#fff";
                ctx.font = "15px YaHei";
                ctx.fillText("￥", 14 * that.data.rpx, 213 * that.data.rpx);
                ctx.font = "22px ArialMT";
                ctx.fillText(item.before_price, 27 * that.data.rpx, 213 * that.data.rpx);
                ctx.font = "10px YaHei";
                ctx.fillText("￥" + item.original_price, 91.5 * that.data.rpx, 213 * that.data.rpx);
                var low_oprice_width = ctx.measureText("￥" + item.original_price).width;
                ctx.strokeStyle = "#fff";
                ctx.setLineWidth = 2 * that.data.rpx;
                ctx.moveTo(91.5 * that.data.rpx, 210 * that.data.rpx);
                ctx.lineTo((91.5 + low_oprice_width) * that.data.rpx, 210 * that.data.rpx);
                ctx.stroke();
                ctx.fillStyle = "#fff";
                ctx.font = "10px YaHei";
                ctx.fillText("已售" + item.order_num + "份", 14 * that.data.rpx, 233 * that.data.rpx);
                ctx.strokeStyle = "#FB7E7E";
                ctx.setLineWidth = 1 * that.data.rpx;
                ctx.moveTo(70 * that.data.rpx, 223 * that.data.rpx);
                ctx.lineTo(70 * that.data.rpx, 233 * that.data.rpx);
                ctx.stroke();
                if (that.data.sku_num_display == 1) {
                    ctx.fillStyle = "#fff";
                    ctx.font = "10px YaHei";
                    ctx.fillText("还剩" + item.stock_number + "件", 78 * that.data.rpx, 233 * that.data.rpx);
                }
                ctx.fillStyle = "#884A10";
                ctx.font = "normal bold 14px YaHei";
                ctx.fillText("立即抢购>", 220 * that.data.rpx, 225 * that.data.rpx);
                ctx.draw(true, () => {
                    wx.canvasToTempFilePath({
                        canvasId: "shareCanvas",
                        fileType: "png",
                        success: function(res) {
                            that.setData({
                                shareId: item.id,
                                shareTitle: item.title,
                                shareCanvasPhoto: res.tempFilePath,
                                alert2: 1
                            });
                            wx.hideLoading();
                        },
                        fail: function(res) {
                            that.setData({
                                shareId: item.id,
                                shareTitle: item.title,
                                imgURL: item.img,
                                alert2: 1
                            });
                            wx.hideLoading();
                        },
                        complete: function(res) {}
                    }, that);
                });
            }
        });
    },
    getKillProductDetail: function() {
        var that = this;
        var id = that.data.pro_id;
        var time_id = that.data.share_kill_time;
        common.request({
            endpoint: "product/product_detail",
            method: "post",
            data: {
                id: id,
                visit_type: 1,
                time_id: time_id
            },
            success: res => {
                let details = res.extra;
                that.setData({
                    proDetails: details,
                    pro_share: true
                });
                that.setKillEndDown(details.timing);
            }
        });
    },
    //分享秒杀倒计时
    setKillEndDown: function(times) {
        var that = this;
        var kill_end_timer = null;
        kill_end_timer = setInterval(function() {
            var day = 0, hour = 0, minute = 0, second = 0;
            //时间默认值
                        if (times > 0) {
                hour = Math.floor(times / (60 * 60)) - day * 24;
                minute = Math.floor(times / 60) - day * 24 * 60 - hour * 60;
                second = Math.floor(times) - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60;
            }
            if (hour <= 9) hour = "0" + hour;
            if (minute <= 9) minute = "0" + minute;
            if (second <= 9) second = "0" + second;
            that.setData({
                kill_end_hour: hour,
                kill_end_minute: minute,
                kill_end_second: second
            });
            times--;
        }, 1e3);
        if (times <= 0) {
            clearInterval(timer);
        }
    },
    //产品主数据-
    getProductDetail: function() {
        var that = this;
        var id = that.data.pro_id;
        common.request({
            endpoint: "product/product_detail",
            method: "post",
            data: {
                id: id,
                visit_type: 1
            },
            success: res => {
                let details = res.extra;
                that.setData({
                    proDetails: details,
                    pro_share: true
                });
                that.setEndDown();
            },
            fail(err) {}
        });
    },
    setEndDown: function() {
        let that = this;
        let sell_ended_at = that.data.proDetails.sell_ended_at;
        var time1 = new Date();
        var time2 = new Date(sell_ended_at);
        var leave = time2.getTime() - time1.getTime();
        that.data.setLeaveInterval = setInterval(function() {
            var day = Math.floor(leave / (36e5 * 24));
            var hour = Math.floor(leave / 36e5) - day * 24;
            var minute = Math.floor(leave / (1e3 * 60)) - day * 24 * 60 - hour * 60;
            var second = Math.floor(leave / 1e3) - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60;
            if (day <= 9) day = "0" + day + "天";
            if (hour <= 9) hour = "0" + hour;
            if (minute <= 9) minute = "0" + minute;
            if (second <= 9) second = "0" + second;
            that.setData({
                end_day: day,
                end_hour: hour,
                end_minute: minute,
                end_second: second
            });
            leave = leave - 1e3;
        }, 1e3);
        if (leave <= 0) {
            clearInterval(that.data.setLeaveInterval);
        }
    },
    hideProModal: function() {
        let that = this;
        that.setData({
            pro_share: false
        });
    },
    //*******************************************************
    //
    // 整理合并首页所有请求 hgj 2019.11.03
    // 下面为封装的共用方法调用
    // 主要为用户信息获取和团长信息获取  common 和 leader
    //
    //*******************************************************
    //首页弹窗
    getUserInfo: function() {
        common.getUserInfo();
    },
    //团长切换共用方法调用
    chooseButt: function(e) {
        leader.chooseButt(e);
    },
    startmessage: function() {
        wx.showModal({
            title: "发送成功",
            content: "请长按通知消息内的二维码加群"
        });
    },
    //页面请求开始
    requestStart: function(openid) {
        let that = this;
        common.getBottomIcon(1).then(res => {
            common.getCart();
        });
        leader.getMyLeaderInfo_aync(that.data.openid, that.data.s_leader[1]).then(() => {
            //需要leader_id才能有的模块
            if (that.data.isRefresh) {
                that.getKilltime();
                //秒杀
                                that.getSpell();
                //拼团
                        }
            //  that.getClass(openid); //商品开始
                });
        that.getBase(openid);
        //基础配置
        //会员状态
                that.getVipStatus();
        //无需判断的请求，直接在此请求
                that.getSow();
        //轮播图
                that.getHome();
        //专题活动
        //下面的请求，需要在appbase里做返回开关
                that.getDiscount(openid);
        //弹出红包
                that.getNotice();
        //公告
                that.getNavData();
        //导航
                if (this.selectComponent("#nav")) {
            this.Nav = this.selectComponent("#nav");
        }
        that.getIndexdiscount(openid);
        //红包广场
        //营销模块
                that.getNewUserProduct(openid);
        //新人商品
                if (that.data.isRefresh) {
            that.getProLimit(openid);
            //获取限量商品
                }
        //获取个人信息
                that.getMyInfo();
        //是否有奖励
                that.shareAward();
        //是否有待领取
        //that.billCheck();
                that.getClass(that.data.openid);
        //商品开始
                that.getProLimit(that.data.openid);
    },
    //接龙列表
    getDragonList: function() {
        let that = this;
        return new Promise((resolve, reject) => {
            common.request({
                endpoint: "group-solit/list",
                method: "post",
                data: {
                    uniacid: un.uniacid,
                    openid: wx.getStorageSync("user").openid
                },
                header: {},
                success: function(res) {
                    if (res.code == 0) {
                        res.extra.forEach(item => {
                            item.pro_images = item.products.map(product => {
                                return product.icon;
                            });
                        });
                        that.setData({
                            drangonList: res.extra,
                            showLoading: 0
                        });
                    }
                    resolve();
                },
                fail(res) {
                    wx.showModal({
                        title: that.data.alert_title,
                        contnet: res.message,
                        showCancel: false
                    });
                    reject(res);
                }
            });
        });
    },
    billCheck: function() {
        common.request({
            endpoint: "/Random/manage/bill-check",
            method: "post",
            data: {},
            success: res => {
                var bill_id = res.extra.bill_id;
                if (res.code == 0) {
                    wx.showModal({
                        title: "提示",
                        content: res.message,
                        confirmText: "前往领取",
                        success(res) {
                            if (res.confirm) {
                                wx.navigateTo({
                                    url: `/random/pages/center/center?id=${bill_id}`
                                });
                            }
                        }
                    });
                }
            },
            fail(res) {}
        });
    },
    shareAward: function() {
        common.request({
            endpoint: "Random/manage/share-award",
            method: "post",
            data: {},
            success: res => {
                wx.showToast({
                    icon: "none",
                    title: res.message,
                    duration: 3e3
                });
            }
        });
    },
    getLocationSet: function() {
        var that = this;
        return new Promise((resolve, reject) => {
            common.request({
                endpoint: "set/app_base",
                method: "get",
                data: {},
                success: res => {
                    that.setData({
                        master_auto_location: res.extra.master_auto_location ? res.extra.master_auto_location : 0
                    });
                    resolve();
                }
            });
        });
    },
    //全局基础配置信息
    getBase: function(openid) {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                if (res.extra.copyright_msg) {
                    var copy = res.extra.copyright_msg;
                    var copyText = [];
                    if (copy.indexOf(",") != -1) {
                        copyText = copy.split(",");
                    } else {
                        copyText[0] = copy;
                    }
                } else {
                    copyText = "";
                }
                that.setData({
                    color_header: res.extra.color_header,
                    color_text: res.extra.color_text,
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    title: res.extra.title,
                    style: res.extra.style,
                    leader_change: res.extra.l_change,
                    is_open: res.extra.is_open,
                    copyImg: res.extra.copyright_img,
                    copyText: copyText,
                    time_s: res.extra.time_s,
                    time_e: res.extra.time_e,
                    phone: res.extra.phone,
                    orderlist: res.extra.orderlist,
                    sleep_img: res.extra.sleep_img,
                    is_mcity: res.extra.is_mcity,
                    rp_name: res.extra.rp_name,
                    share_index: res.extra.share_index,
                    //首页分享图链接
                    share_title: res.extra.share_title ? res.extra.share_title : res.extra.title,
                    //首页分享标题
                    if_search_index: res.extra.if_search_index,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    lock_fans: res.extra.lock_fans,
                    leader_style: res.extra.leader_style,
                    animation_img: res.extra.animation_img,
                    cate_navigation: res.extra.cate_navigation,
                    plant_show: res.extra.plant_show,
                    plant_bg: res.extra.plant_bg,
                    header_bg: res.extra.header_bg ? res.extra.header_bg : that.data.domain + "img/top.png",
                    is_new_style: res.extra.is_new_style,
                    new_style_color: res.extra.new_style_color,
                    is_leder_style: res.extra.is_leder_style,
                    leader_style_color: res.extra.leader_style_color,
                    is_limit_style: res.extra.is_limit_style,
                    limit_style_color: res.extra.limit_style_color,
                    is_seckill_style: res.extra.is_seckill_style,
                    seckill_style_color: res.extra.seckill_style_color,
                    seckill_style: res.extra.seckill_style,
                    buddy_title: res.extra.buddy_title,
                    buddy_img: res.extra.buddy_img,
                    wxapp_img: res.extra.wxapp_img,
                    quick_share: res.extra.quick_share,
                    share_type: res.extra.share_type,
                    share_link: res.extra.share_link,
                    sku_display: res.extra.sku_display,
                    new_member_audit: res.extra.new_member_audit,
                    userAuditStatus: res.extra.userAuditStatus ? res.extra.userAuditStatus : 2,
                    //会员审核状态，1待审核，2正常使用，3需申请、重新申
                    custom_title: res.extra.level_set.custom_title,
                    service_qr_switch: res.extra.service_qr_switch,
                    service_qr: res.extra.service_qr,
                    level_set: res.extra.level_set,
                    level_display: res.extra.level_display,
                    sku_num_display: res.extra.sku_num_display,
                    sale_time_show: res.extra.sale_time_show,
                    special_custom_name: res.extra.special_custom_name,
                    //专享资金
                    group_list_show: res.extra.group_list_show,
                    //0隐藏，1展示
                    t_cart_num: res.extra.cart_total_num
                });
                //处理模块开关
                                var features = common.getModulesSwich(res.extra.features);
                //处理数据格式
                                that.setData({
                    features: features
                });
                if (that.data.features.consumptionAward && that.data.features.consumptionAward == 1) {
                    that.awardCreate();
                }
                //最后一个风格 有倒计时
                                if (res.extra.style == 5) {
                    clearInterval(that.data.setInterval);
                    that.countdown();
                }
                that.getLiveList();
                //直播间列表
                                if (that.data.s_uid) {
                    // console.log('测试走不走')
                    that.levelShare();
                }
                if (that.data.group_list_show == 1) {
                    that.getDragonList();
                }
            }
        });
    },
    //显示二维码
    showQrService: function() {
        let service_qr = [ this.data.service_qr ];
        wx.previewImage({
            urls: service_qr
        });
    },
    //专题活动
    getHome: function() {
        let that = this;
        common.request({
            endpoint: "Thematic/thematic/home_list",
            method: "post",
            success: res => {
                that.setData({
                    homeList: res.extra
                });
            }
        });
    },
    getMyInfo: function() {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        common.request({
            endpoint: "My/myinfo/myinfo",
            method: "post",
            data: {
                openid: openid
            },
            success: res => {
                that.setData({
                    info: res.extra
                });
            }
        });
    },
    /**获取消费奖励 */
    awardCreate: function() {
        var that = this;
        common.request({
            endpoint: "Award/award/index-query",
            method: "post",
            data: {},
            success: res => {
                if (res.extra.length) {
                    res.extra.map(x => {
                        x.awardBox = 1;
                    });
                    that.setData({
                        awardList: res.extra
                    });
                }
            }
        });
    },
    /**领取消费奖励 */
    receive_award: function(e) {
        let that = this;
        let id = e.currentTarget.dataset.id;
        common.request({
            endpoint: "Award/award/draw",
            method: "post",
            data: {
                activity_id: id
            },
            success: res => {
                wx.showToast({
                    title: "领取成功"
                });
                var awardList = that.data.awardList;
                awardList.map(x => {
                    if (x.id == id) {
                        x.awardBox = 0;
                    }
                });
                this.setData({
                    awardList: awardList
                });
            },
            fail(err) {
                var awardList = that.data.awardList;
                awardList.map(x => {
                    if (x.id == id) {
                        x.awardBox = 0;
                    }
                });
                this.setData({
                    awardList: awardList
                });
                wx.showModal({
                    title: that.data.alert_title,
                    content: err.message,
                    showCancel: false
                });
            }
        });
    },
    close_award: function(e) {
        let that = this;
        let id = e.currentTarget.dataset.id;
        var awardList = that.data.awardList;
        awardList.map(x => {
            if (x.id == id) {
                x.awardBox = 0;
            }
        });
        this.setData({
            awardList: awardList
        });
    },
    //直播列表
    getLiveList: function() {
        let that = this;
        if (that.data.features.live == 1) {
            common.request({
                endpoint: "Live/livelist/live_list",
                method: "post",
                data: {
                    form: "index"
                },
                success: res => {
                    that.setData({
                        liveList: res.extra
                    });
                }
            });
        }
    },
    // 轮播图
    getSow: function() {
        var that = this;
        common.request({
            endpoint: "JumpLink/jump_link/link_object",
            method: "post",
            success: res => {
                var imgUrls2 = [];
                var img_advert = [];
                if (res.extra[0]) {
                    imgUrls2 = res.extra[0].img;
                }
                if (res.extra[0]) {
                    img_advert = res.extra[0].img_ad;
                }
                that.setData({
                    imgUrls2: imgUrls2,
                    img_advert: img_advert
                });
                //请求完之后 再请求首页的历史购买数据
                                if (that.data.orderlist == 1 || that.data.orderlist == 2 || that.data.orderlist == 3) {
                    that.getBuyList();
                }
            }
        });
    },
    //首页红包（记得加索引）
    getDiscount: function(openid) {
        var that = this;
        var openid = openid ? openid : wx.getStorageSync("user").openid;
        common.request({
            endpoint: "Voucher/biggifts/show",
            method: "post",
            data: {
                openid: openid
            },
            success: res => {
                var discount;
                if (res.extra.length > 0) {
                    discount = 1;
                } else {
                    discount = 0;
                }
                that.setData({
                    discount_info: res.extra,
                    discount: discount
                });
            }
        });
    },
    //购买列表（1,3数据合并为1个）
    getBuyList: function() {
        var that = this;
        common.request({
            endpoint: "zhongxiang/index_pagination",
            method: "post",
            data: {
                page: 1,
                pageSize: 5
            },
            success: res => {
                that.setData({
                    buylist: res.extra
                });
            }
        });
    },
    //公告列表
    getNotice: function() {
        var that = this;
        common.request({
            endpoint: "set/indexnotice",
            method: "post",
            success: res => {
                that.setData({
                    notice: res.extra
                });
            }
        });
    },
    //nav导航信息
    getNavData() {
        let that = this;
        common.request({
            endpoint: "page/custom_nav",
            method: "post",
            data: {},
            success(res) {
                if (res.data) {
                    var navData = [];
                    if (!!res.data.navData) {
                        navData.push(res.data.navData);
                    }
                    that.setData({
                        cateNav: res.data.navData,
                        getNavData: {
                            navData: navData,
                            show_index: res.data.show_index,
                            styleData: {
                                ...res.data.styleData
                            }
                        }
                    });
                    if (that.Nav) {
                        that.Nav.processData();
                        //导航重新处理
                                        }
                }
            }
        });
    },
    //红包广场
    getIndexdiscount: function(openid) {
        var that = this;
        var openid = openid ? openid : wx.getStorageSync("user").openid;
        common.request({
            endpoint: "Voucher/voucher/list",
            method: "post",
            data: {
                openid: openid,
                type: "index"
            },
            success: res => {
                let aaa = [];
                res.extra.forEach((item, indx) => {
                    item.redPackageChange = false;
                    aaa.push(item);
                });
                if (that.data.redPackage_id) {
                    aaa.forEach((item, index) => {
                        if (that.data.redPackage_id == item.id) {
                            if (item.receive == 0 || item.stock_num == 0) {
                                item.redPackageChange = true;
                                if (!that.data.redPackageChange) {
                                    that.setData({
                                        index_discount: aaa,
                                        redPackage_flag: false
                                    });
                                } else {
                                    that.setData({
                                        redPackage: aaa,
                                        redPackage_flag: true
                                    });
                                }
                            } else {
                                that.setData({
                                    redPackage: aaa,
                                    redPackage_flag: true
                                });
                            }
                        }
                    });
                } else {
                    that.setData({
                        index_discount: aaa,
                        redPackage_flag: false
                    });
                }
            }
        });
    },
    //秒杀模块
    getKilltime: function() {
        var that = this;
        common.request({
            endpoint: "Seckill/show/tick-tock",
            method: "post",
            data: {},
            header: {},
            success: function(res) {
                let kill_list = res.extra;
                if (res.extra.length) {
                    that.setData({
                        sale_box: that.data.sale_box + 1
                    });
                }
                kill_list.map(x => {
                    if (x.time) {
                        x.char_time = that.makeTimes(x.time);
                    }
                });
                //下面为首页整列样式秒杀数据格式，区多长秒杀数据
                                that.setData({
                    kill_list: kill_list
                });
                for (var i = 0; i < kill_list.length; i++) {
                    if (kill_list[i].flag == 1) {
                        that.setData({
                            kill_now_id: "s" + kill_list[i].id,
                            time_id: kill_list[i].id,
                            kill_time: kill_list[i].time,
                            char_time: kill_list[i].char_time,
                            time_flag: kill_list[i].flag
                        });
                        break;
                    } else if (kill_list[i].flag == 0) {
                        that.setData({
                            kill_now_id: "s" + kill_list[i].id,
                            time_id: kill_list[i].id,
                            kill_time: kill_list[i].time,
                            char_time: kill_list[i].char_time,
                            time_flag: kill_list[i].flag
                        });
                        break;
                    }
                }
                //存在进行中的秒杀，则优先显示进行中的秒杀
                //如果秒杀全部结束，显示最后一场秒杀
                                if (that.data.time_id == "" && res.extra.length > 0) {
                    var arr = that.data.kill_list;
                    that.setData({
                        kill_now_id: "s" + arr[arr.length - 1].id,
                        time_id: arr[arr.length - 1].id,
                        char_time: arr[arr.length - 1].char_time,
                        time_flag: arr[arr.length - 1].flag
                    });
                }
                that.getKillpro();
            }
        });
    },
    chooseKillPro(e) {
        this.setData({
            time_id: e.currentTarget.dataset.timeid,
            index_cc: e.currentTarget.dataset.index
        });
        this.getKillpro();
    },
    makeTimes: function(time) {
        var str = time;
        var arr = str.split(":");
        var hour = Number(arr[0]) + "点";
        var min = Number(arr[1]) + "分";
        return hour + min;
    },
    //秒杀模块商品
    getKillpro: function() {
        var that = this;
        var time_id = that.data.time_id;
        var leaderinfo = that.data.myleaderinfo;
        common.request({
            endpoint: "Seckill/show/product",
            method: "post",
            data: {
                time_id: time_id,
                leaderId: leaderinfo.leader_id,
                page: 1
            },
            header: {},
            success: function(res) {
                that.setData({
                    kill_pro: res.extra
                });
            }
        });
    },
    //拼团模块及商品
    getSpell: function() {
        let that = this;
        let leader_id = that.data.myleaderinfo.leader_id;
        common.request({
            endpoint: "Groupbuy/reco/index_rec",
            method: "post",
            data: {
                leaderId: leader_id
            },
            header: {},
            success: function(res) {
                if (res.extra.rows.length > 0) {
                    that.setData({
                        spell_goods: res.extra.rows,
                        sale_box: that.data.sale_box + 1
                    });
                } else {
                    that.setData({
                        spell_goods: []
                    });
                }
            }
        });
    },
    //获取新用户专享商品
    getNewUserProduct: function(openid) {
        let that = this;
        var openid = openid ? openid : wx.getStorageSync("user").openid;
        common.request({
            endpoint: "product/new_customer_product_list",
            method: "post",
            data: {
                open_id: openid
            },
            success: res => {
                if (!!res.extra.length > 0) {
                    that.setData({
                        isNewCustomer: res.extra,
                        sale_box: that.data.sale_box + 1
                    });
                } else {
                    that.setData({
                        isNewCustomer: []
                    });
                }
            }
        });
    },
    //获取限量商品
    getProLimit: function(openid) {
        let that = this;
        common.request({
            endpoint: "product/pro_limit",
            method: "post",
            data: {
                open_id: openid
            },
            success: res => {
                if (res.extra.length > 0) {
                    that.setData({
                        limit_goods: res.extra,
                        sale_box: that.data.sale_box + 1
                    });
                } else {
                    that.setData({
                        limit_goods: []
                    });
                }
            }
        });
    },
    //首页商品模块，先获取分类，再取商品
    getClass: function(openid) {
        this.setData({
            index_choose: this.data.index_choose,
            page: 1,
            list: [],
            showLoading: 1,
            allBottom: 0,
            goods: []
        });
        common.request({
            endpoint: "product/classification",
            method: "post",
            data: {
                page_type: 0,
                index_show: 1
            },
            header: {
                openid: openid
            },
            success: res => {
                if (!res.extra.data[0]) {
                    var chooseClass = -1;
                } else {
                    var chooseClass = res.extra.data[0].id;
                    this.setData({
                        classification: res.extra.data
                    });
                }
                this.setData({
                    chooseClass: chooseClass
                });
                //商超商品
                                if (chooseClass == "local2") {
                    this.getSuperGoods();
                } else {
                    this.getIndexNewGoods(chooseClass, 1);
                }
            }
        });
    },
    //根据当前分类获取对应产品列表
    getIndexNewGoods: function(chooseClass, newclass) {
        var that = this;
        var page = that.data.page;
        var a_sale = parseInt(that.data.index_choose);
        var leader_id_true = that.data.myleaderinfo.leader_id_true ? that.data.myleaderinfo.leader_id_true : -1;
        that.getProductIndex(chooseClass, page, a_sale, leader_id_true);
    },
    //获取最终商品列表
    getProductIndex(chooseClass, page, a_sale, leader_id_true) {
        this.setData({
            showLoading: 1,
            allBottom: 0
        });
        let that = this;
        common.request({
            endpoint: "product/class_product_index",
            method: "post",
            data: {
                pid: chooseClass,
                a_sale: a_sale,
                page: page,
                leader_id_true: leader_id_true
            },
            success: function(res) {
                var data = that.data.goods;
                if (res.extra.length < 1) {
                    let goods = [];
                    that.setData({
                        allBottom: 2,
                        showLoading: 0,
                        goods: that.data.page == 1 ? res.extra : that.data.goods,
                        local_goods: that.data.page == 1 ? res.extra : that.data.local_goods,
                        brandShow: 1
                    });
                } else {
                    if (res.extra[0].hasOwnProperty("attr")) {
                        var proInfo = that.changeProInfo(res.extra);
                        if (proInfo.length) {
                            //规格
                            proInfo.map(item => {
                                let sku_attribute = item.sku_attribute;
                                var arr_sku = [];
                                var arr_sku_str = [];
                                sku_attribute.map(item => {
                                    var arr_sku_item = [];
                                    item.attribute_value.forEach((subItem, index) => {
                                        arr_sku_item.push(subItem.value);
                                    });
                                    arr_sku.push(arr_sku_item);
                                });
                                arr_sku = that.cartesianProductOf(...arr_sku);
                                arr_sku.map(item => {
                                    arr_sku_str.push(item.join("/"));
                                });
                                item.arr_sku = arr_sku;
                                item.arr_sku_str = arr_sku_str;
                            });
                        }
                        let goods = page == 1 ? proInfo : data.concat(proInfo);
                        that.setData({
                            brandShow: 0,
                            goods: goods,
                            isLocal: 0,
                            showLoading: 0,
                            page: page + 1,
                            hasMore: true
                        });
                    } else {
                        var local_goods_x = res.extra;
                        local_goods_x.map(x => {
                            x.really_sale = Number(x.virtual_monthly_sales) + Number(x.sale_volume);
                            let leader_brokerage = Number(x.leader_brokerage) / 100;
                            x.brokerage = (x.sale_price * leader_brokerage).toFixed(2);
                        });
                        let local_goods = page == 1 ? local_goods_x : that.data.local_goods.concat(local_goods_x);
                        that.setData({
                            local_goods: local_goods,
                            isLocal: 1,
                            showLoading: 0,
                            page: page + 1,
                            hasMore: true
                        });
                    }
                }
            }
        });
    },
    /**
   * 计算所有规格属性
   */
    cartesianProductOf() {
        return Array.prototype.reduce.call(arguments, function(a, b) {
            var ret = [];
            a.forEach(function(a) {
                b.forEach(function(b) {
                    ret.push(a.concat([ b ]));
                });
            });
            return ret;
        }, [ [] ]);
    },
    //*******************************************************
    //
    // 整理合并首页所有请求 hgj 2019.11.03
    // 下面为非页面加载后的直接请求
    // 都是一些点击触发的方法
    //
    //
    //*******************************************************
    //选择团长 判断权限
    goToChooseLeader(e) {
        if (this.data.leader_change != 1) return;
        $author({
            url: e.currentTarget.dataset.url
        });
    },
    //进入产品详情 判断权限 不可以合并吗
    goToDetail(e) {
        if (this.data.userAuditStatus != 2 && this.data.new_member_audit == 1) {
            wx.showModal({
                title: "提示",
                content: "你还不是会员，请先到个人中心申请吧！",
                showCancel: false
            });
            return false;
        }
        wx.navigateTo({
            url: e.currentTarget.dataset.url
        });
    },
    contact(e) {},
    goToSuperDetail(e) {
        wx.navigateTo({
            url: "/localLifePackage/pages/superMarket_detail/superMarket_detail?id=" + e.currentTarget.dataset.id + "&business_id=" + e.currentTarget.dataset.businessid
        });
    },
    //领取弹出的红包
    receive_label: function(e) {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        var discount_info = that.data.discount_info;
        var discount_index = e.currentTarget.dataset.index;
        var id = e.currentTarget.dataset.id;
        $author({
            success() {
                common.request({
                    endpoint: "Voucher/voucher/draw",
                    method: "post",
                    data: {
                        openid: openid,
                        gift_id: id
                    },
                    success: res => {
                        wx.showToast({
                            title: res.message
                        });
                        if (discount_index < discount_info.length - 1) {
                            discount_index++;
                            that.setData({
                                discount_index: discount_index
                            });
                        } else {
                            that.setData({
                                discount: 0
                            });
                        }
                    }
                });
            }
        });
    },
    //关闭红包
    close_discount: function(e) {
        var that = this;
        var discount_info = that.data.discount_info;
        var discount_index = e.currentTarget.dataset.index;
        if (discount_index < discount_info.length - 1) {
            discount_index++;
            that.setData({
                discount_index: discount_index
            });
        } else {
            that.setData({
                discount: 0
            });
        }
    },
    //跳转红包广场
    goToRedMarket() {
        wx.navigateTo({
            url: "/pages/discount_square/discount_square"
        });
    },
    //专场活动领取红包
    getRedPackage(e) {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        var id = e.detail.id;
        var i = e.currentTarget.dataset.index;
        $author({
            success() {
                common.request({
                    endpoint: "Voucher/voucher/draw",
                    method: "post",
                    data: {
                        openid: openid,
                        vor_id: id
                    },
                    success: res => {
                        if (res.code == 0) {
                            if (res.message == "红包领取成功") {
                                wx.showToast({
                                    title: res.message
                                });
                                that.data.homeList.brand[i].voucher.forEach((item, index) => {
                                    if (id == item.id) {
                                        if (item.receive == 1) {
                                            that.setData({
                                                redPackageSmallFlag: true
                                            });
                                        }
                                    }
                                });
                            }
                            that.getHome();
                        }
                    },
                    fail: res => {
                        wx.showToast({
                            title: res.message
                        });
                    }
                });
            }
        });
    },
    //公告详情
    notice_detail: function(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        common.request({
            endpoint: "set/indexnotice",
            method: "post",
            data: {
                id: id
            },
            success: res => {
                that.setData({
                    notice_content: res.extra,
                    notice_alert: 1
                });
            }
        });
    },
    //关闭公告
    close_notice: function() {
        var that = this;
        that.setData({
            notice_alert: 0
        });
    },
    //领取红包
    receiveDiscount: function(e) {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        var id = e.detail.id;
        that.setData({
            redPackage_id: id
        });
        $author({
            success() {
                common.request({
                    endpoint: "Voucher/voucher/draw",
                    method: "post",
                    data: {
                        openid: openid,
                        vor_id: id
                    },
                    success: res => {
                        if (that.data.redPackage.length > 0) {
                            that.data.redPackage.forEach((item, index) => {
                                if (id == item.id) {
                                    if (item.receive == 1) {
                                        that.setData({
                                            redPackageChange: true
                                        });
                                    }
                                }
                            });
                        } else {
                            that.data.index_discount.forEach((item, index) => {
                                if (id == item.id) {
                                    if (item.receive == 1) {
                                        that.setData({
                                            redPackageChange: true
                                        });
                                    }
                                }
                            });
                        }
                        that.getIndexdiscount(openid);
                        wx.showToast({
                            title: res.message
                        });
                    }
                });
            }
        });
    },
    //切换团长
    leader_change: function(e) {
        var that = this;
        var address = e.currentTarget.dataset.address;
        var leaderName = this.data.leaderName;
        var iam_leader = this.data.myleaderinfo.iam_leader;
        if (this.data.leader_change == 1) {
            if (iam_leader == 1) {
                wx.showModal({
                    title: that.data.alert_title,
                    content: "您自己是" + leaderName + "，仅可以查看附近" + leaderName + "！",
                    confirmText: "查看附近",
                    success(res) {
                        if (res.confirm) {
                            wx.navigateTo({
                                url: "/pages/nearby_group2/nearby_group2"
                            });
                        }
                    }
                });
            } else {
                wx.navigateTo({
                    url: "/pages/nearby_group2/nearby_group2"
                });
            }
        }
    },
    //幻灯片切换
    swiperChange: function(e) {
        this.setData({
            currentIndex: e.detail.current
        });
    },
    //首页电话
    index_call: function(e) {
        var phone = e.currentTarget.dataset.phone;
        wx.makePhoneCall({
            phoneNumber: phone
        });
    },
    //页面下拉
    onPageScroll: function(e) {
        let that = this;
        if (that.data.cate_navigation == 0) {
            const query = wx.createSelectorQuery().in(this);
            query.select("#classid").boundingClientRect();
            query.selectViewport().scrollOffset();
            query.exec(function(res) {
                if (res[0]) {
                    if (res[0].top <= 38) {
                        that.setData({
                            floorstatus: true,
                            nav_fixed: "nav_fixed"
                        });
                    } else {
                        that.setData({
                            floorstatus: false,
                            nav_fixed: "nav_normal"
                        });
                    }
                }
            });
        } else {
            const query1 = wx.createSelectorQuery().in(this);
            query1.select("#nav").boundingClientRect();
            query1.selectViewport().scrollOffset();
            query1.exec(function(res) {
                if (res[0]) {
                    if (res[0].top <= 0) {
                        that.setData({
                            floorstatus: true,
                            cate_fixed: "nav_fixed"
                        });
                    } else {
                        that.setData({
                            floorstatus: false,
                            cate_fixed: "nav_normal"
                        });
                    }
                }
            });
        }
    },
    getMasterUniacid_new: function() {
        let that = this;
        return new Promise((resolve, reject) => {
            common.request({
                endpoint: "DIY/new-entry/master-uniacid",
                method: "post",
                data: {
                    uniacid: un.uniacid
                },
                header: {},
                success: function(res1) {
                    that.setData({
                        masterUniacid: res1.extra.masterUniacid
                    });
                    // wx.getLocation({
                    //     type: "gcj02",
                    //     isHighAccuracy: true,
                    //     success: function(res2) {
                    //         that.setData({
                    //             latitude: res2.latitude,
                    //             longitude: res2.longitude
                    //         });
                    //         common.request({
                    //             endpoint: "DIY/new-entry/auto-city",
                    //             method: "post",
                    //             data: {
                    //                 masterUniacid: that.data.masterUniacid,
                    //                 latitude: that.data.latitude,
                    //                 longitude: that.data.longitude
                    //             },
                    //             header: {},
                    //             success: function(res3) {
                    //                 that.setData({
                    //                     cityInfo: res3.extra
                    //                 });
                    //                 wx.setStorageSync("uniacid", res3.extra.autoUniacid);
                    //             }
                    //         });
                    //     },
                    //     fail: function(res) {}
                    // });
                }
            });
            resolve();
        });
    },
    //一键回到顶部
    goTop: function(e) {
        wx.pageScrollTo({
            scrollTop: 0
        });
    },
    //切换下期预告产品
    index_choose: function(e) {
        var that = this;
        var a_sale = e.currentTarget.dataset.asale;
        that.setData({
            index_choose: a_sale,
            page: 1,
            list: [],
            showLoading: 1,
            allBottom: 0,
            goods: []
        });
        that.getClass();
    },
    //跳转页面
    goToPages(e) {
        var that = this;
        $author({
            success() {
                customLink(e.detail.itemData);
            }
        });
    },
    goToPages1(e) {
        var that = this;
        $author({
            success() {
                customLink(e.currentTarget.dataset.itemdata);
            }
        });
    },
    //跳转广告 跟上面的一样 可以合并吗？
    goToPages2(e) {
        var that = this;
        $author({
            success() {
                customLink(e.currentTarget.dataset.itemdata);
            }
        });
    },
    //跳转商品详情
    toDetail: function(e) {
        var id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: "/pages/pro_detail/pro_detail?id=" + id
        });
    },
    //关闭蒙层
    close_alert: function(e) {
        this.setData({
            alert: 0
        });
    },
    //手动切换商品分类
    chooseClass: function(e) {
        var that = this;
        var a_sale = parseInt(that.data.index_choose);
        var id = e.currentTarget.dataset.id;
        var index = e.currentTarget.dataset.index;
        if (index > 2) {
            var index = index - 2;
            that.setData({
                scrollId: "text" + index
            });
        }
        that.setData({
            showLoading: 1,
            allBottom: 0,
            page: 1,
            chooseClass: id
        });
        //商超商品
                if (id == "local2") {
            this.setData({
                isLocal: 2
            });
            this.getSuperGoods();
        } else {
            this.getIndexNewGoods(id, 1);
        }
    },
    getSuperGoods() {
        var that = this;
        common.request({
            endpoint: "v1/Supermarket/product",
            method: "post",
            data: {
                page: that.data.super_page,
                index: 1
            },
            header: {},
            success: function(res) {
                var data = that.data.super_goods;
                if (res.extra.rows.length < 1) {
                    let goods = [];
                    that.setData({
                        allBottom: 2,
                        super_goods: that.data.super_goods,
                        brandShow: 1
                    });
                } else {
                    var superGoods = res.extra.rows;
                    let super_goods = that.data.super_page == 1 ? superGoods : that.data.super_goods.concat(superGoods);
                    that.setData({
                        super_goods: super_goods,
                        isLocal: 2,
                        super_page: that.data.super_page + 1,
                        hasMore: true
                    });
                }
            }
        });
    },
    //获取是否授权，是否需要提示
    continueGetSet: function() {
        let that = this;
        wx.getSetting({
            success(res) {
                if (res.authSetting["scope.userLocation"] == false) {
                    that.setData({
                        showInfoTip: true
                    });
                }
                if (res.authSetting["scope.userLocation"] == true) {
                    that.setData({
                        showInfoTip: false
                    });
                }
            }
        });
    },
    //获取助战的uniacid
    getMasterUniacid: function() {
        let that = this;
        common.request({
            endpoint: "DIY/new-entry/master-uniacid",
            method: "post",
            data: {
                uniacid: un.uniacid
            },
            header: {},
            success: function(res) {
                that.setData({
                    masterUniacid: res.extra.masterUniacid
                });
                // that.getCurrentAddress();
            }
        });
    },
    //获取当前位置
    getCurrentAddress: function() {
        var that = this;
        wx.getLocation({
            type: "gcj02",
            isHighAccuracy: true,
            success: function(res) {
                that.setData({
                    latitude: res.latitude,
                    longitude: res.longitude
                });
                //自动定位当前站点
                                that.getAutoCity();
            },
            fail: function(res) {}
        });
    },
    getAutoCity: function() {
        let that = this;
        common.request({
            endpoint: "DIY/new-entry/auto-city",
            method: "post",
            data: {
                masterUniacid: that.data.masterUniacid,
                latitude: that.data.latitude,
                longitude: that.data.longitude
            },
            header: {},
            success: function(res) {
                that.setData({
                    cityInfo: res.extra
                });
                wx.setStorageSync("uniacid", res.extra.autoUniacid);
            }
        });
    },
    chooseUniacid: function() {
        let that = this;
        that.setData({
            gate_alert: 1
        });
        common.request({
            endpoint: "leader/near_leader",
            method: "post",
            data: {
                address: that.data.latitude + "," + that.data.longitude,
                openid: wx.getStorageSync("user").openid,
                new_city_style: 1
            },
            header: {},
            success: function(res) {
                that.setData({
                    cityList: res.extra
                });
            }
        });
    },
    //选择团长
    setLeaderInfo: function(e) {
        let that = this;
        var id = e.currentTarget.dataset.id;
        var openid = wx.getStorageSync("user").openid;
        common.request({
            endpoint: "member/save_leader_id",
            method: "post",
            data: {
                openid: openid,
                leader_id: id
            },
            success: res => {
                //刷新首页
                that.setData({
                    gate_alert: 0,
                    is_new: 1
                });
                that.onLoad();
            },
            fail(err) {
                if (err.code == 1) {
                    wx.showToast({
                        title: "你是" + that.data.leaderName + ",无法切换" + that.data.leaderName + "!",
                        icon: "none"
                    });
                } else {
                    wx.showToast({
                        title: err.message,
                        icon: "none"
                    });
                }
            }
        });
    },
    hideGateAlert: function() {
        let that = this;
        that.setData({
            gate_alert: 0
        });
    },
    //记录搜索名称
    saveWord: function(e) {
        var that = this;
        var search_con = e.detail.value;
        that.setData({
            search_con: search_con
        });
    },
    //点击搜索
    search: function() {
        var that = this;
        var search_con = that.data.search_con;
        wx.navigateTo({
            url: "/pages/search/search?search=" + search_con
        });
    },
    //点击显示团购信息
    show_group_buy: function() {
        let that = this;
        common.request({
            endpoint: "product/index_product_message",
            method: "post",
            data: {
                openid: wx.getStorageSync("user").openid
            },
            header: {},
            success: function(res) {
                that.setData({
                    group_buy: res.extra,
                    showGroupbuy: 1,
                    alert1: 0
                });
            }
        });
    },
    //关闭团购复制信息
    close_group_buy: function() {
        let that = this;
        that.setData({
            showGroupbuy: 0
        });
    },
    //复制团购信息
    click_copy: function() {
        let that = this;
        let myleaderinfo = that.data.myleaderinfo;
        let group_buy = that.data.group_buy;
        let leaderName = that.data.leaderName;
        var content = "";
        if (myleaderinfo != "") {
            content = leaderName + "：" + myleaderinfo.name + "\n自提点：" + myleaderinfo.other + "\n";
        }
        for (var i = 0; i < group_buy.length; i++) {
            content += "\n" + group_buy[i].title + "\n";
            for (var j = 0; j < group_buy[i].sub.length; j++) {
                content += j + 1 + "【" + group_buy[i].sub[j].title + "】" + group_buy[i].sub[j].price + "元" + "\n";
            }
        }
        wx.setClipboardData({
            data: content,
            success(res) {
                that.setData({
                    showGroupbuy: 0
                });
            }
        });
    },
    //点击版权
    clickVersion: function() {
        let that = this;
        let version = that.data.version;
        if (version.open_mode == 0) {
            wx.makePhoneCall({
                phoneNumber: version.copyright_phone
            });
        } else {
            wx.navigateTo({
                url: "/pages/version/version"
            });
        }
    },
    //跳转视频页面
    ToVideoDetail(e) {
        var id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: "/pages/videoDetail/videoDetail?id=" + id
        });
    },
    //生成海报
    makeposter1: function() {
        let that = this;
        that.setData({
            alert1: 0
        });
        wx.showLoading({
            title: "海报生成中"
        });
        var leaderinfo = that.data.myleaderinfo;
        //获取团长信息
                common.request({
            endpoint: "share/poster_gd3",
            data: {
                name: leaderinfo.name,
                gname: leaderinfo.other,
                address: leaderinfo.title,
                uid: leaderinfo.leader_id_true,
                lid: leaderinfo.leader_id
            },
            method: "post",
            success(res) {
                var resdata = JSON.parse(res);
                if (resdata.code == 4) {
                    wx.hideLoading();
                    that.toastControl(resdata.extra);
                } else {
                    var imgArry = [];
                    imgArry.push(resdata.extra.image[0].url);
                    wx.previewImage({
                        urls: imgArry,
                        success() {
                            wx.hideLoading();
                        }
                    });
                }
            },
            fail(err) {
                wx.hideLoading();
                that.toastControl("该团长暂无商品分享！");
            }
        });
    },
    //生成海报
    makeposter: function() {
        let that = this;
        let goUrl = "/poster/pages/indexShare/indexShare?uid=" + that.data.uid + "&myleaderinfo=" + encodeURIComponent(JSON.stringify(that.data.myleaderinfo));
        wx.navigateTo({
            url: goUrl
        });
    },
    //生成下期预告海报
    makeNextPoster: function() {
        let that = this;
        var leader_id_true = that.data.myleaderinfo.leader_id_true ? that.data.myleaderinfo.leader_id_true : -1;
        common.request({
            endpoint: "product/class_product_index",
            method: "post",
            data: {
                pid: -1,
                a_sale: 1,
                page: 1,
                leader_id_true: leader_id_true
            },
            success: function(res) {
                let goods = res.extra;
                if (!goods.length) {
                    wx.showToast({
                        title: "暂无下期预告商品",
                        icon: "none"
                    });
                    return false;
                }
                let goUrl = "/poster/pages/nextShare/nextShare?goods=" + encodeURIComponent(JSON.stringify(goods)) + "&myleaderinfo=" + encodeURIComponent(JSON.stringify(that.data.myleaderinfo));
                wx.navigateTo({
                    url: goUrl
                });
            }
        });
    },
    //倒计时  可以封装的 现在应该用不到  可能是预售样式要用
    countdown: function() {
        var that = this;
        let close_time = that.data.time_s;
        var arr_time = close_time.split(":");
        let date = new Date();
        let now_hour = date.getHours();
        let now_minute = date.getMinutes();
        let now_second = date.getSeconds();
        let times = (parseInt(arr_time[0]) - parseInt(now_hour)) * 3600 + (parseInt(arr_time[1]) - parseInt(now_minute)) * 60 + parseInt(now_second);
        if (times < 0) {
            times = times + 24 * 3600;
        }
        var timer = null;
        that.data.setInterval = setInterval(function() {
            var day = 0, hour = 0, minute = 0, second = 0;
            //时间默认值
                        if (times > 0) {
                hour = Math.floor(times / (60 * 60)) - day * 24;
                minute = Math.floor(times / 60) - day * 24 * 60 - hour * 60;
                second = Math.floor(times) - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60;
            }
            if (hour <= 9) hour = "0" + hour;
            if (minute <= 9) minute = "0" + minute;
            if (second <= 9) second = "0" + second;
            that.setData({
                hour: hour,
                minute: minute,
                second: second
            });
            times--;
        }, 1e3);
        if (times <= 0) {
            clearInterval(that.data.setInterval);
        }
    },
    //关闭分享弹窗的和分享
    alert_close2: function() {
        var alert1 = this.data.alert1;
        if (alert1 == 0) {
            alert1 = 1;
        } else {
            alert1 = 0;
        }
        this.setData({
            alert1: alert1
        });
    },
    //关闭分享弹窗的和分享
    alert_close3: function() {
        this.setData({
            alert2: this.data.alert2 == 0 ? 1 : 0
        });
    },
    //判断购买资格   -------------- 首页用不到
    isNewCustomer2(id, e) {
        let that = this;
        common.request({
            endpoint: "product/new_customer_judge",
            method: "post",
            data: {
                open_id: wx.getStorageSync("user").openid,
                id: id
            },
            success: res => {
                if (res.code == 0) {
                    that.join_cart_current(e);
                } else {
                    that.toastControl("此商品只能新用户购买哟", 3e3);
                }
            },
            fail() {
                that.toastControl("此商品只能新用户购买哟", 3e3);
            }
        });
    },
    //获取tmplIds
    getTmplIds: function() {
        let that = this;
        const version = wx.getSystemInfoSync().SDKVersion;
        if (util.compareVersion(version, "2.8.2") < 0) {
            that.setData({
                tmplIds: [],
                subscribeMessage: false
            });
            return;
        }
        common.request({
            endpoint: "set/template_get",
            method: "post",
            data: {},
            header: {
                "content-type": "application/json"
            },
            success: res => {
                let tmplIds = [];
                let subscribeMessage = true;
                res.extra.map(v => {
                    if ((v.type == "21" || v.type == "22" || v.type == "23") && v.status == "1") {
                        tmplIds.push(v.template_id);
                    }
                });
                if (!tmplIds.length) {
                    subscribeMessage = false;
                }
                that.setData({
                    tmplIds: tmplIds,
                    subscribeMessage: subscribeMessage
                });
            }
        });
    },
    //*******************************************************
    //
    // 整理合并首页所有请求 hgj 2019.11.03
    // 下面开始是商品添加购物车
    // 怎么这么多行？肯定要合并
    //
    //
    //*******************************************************
    join_cart_share: function(e) {
        let that = this;
        that.join_cart_current(e);
    },
    join_cart: function(e) {
        let that = this;
        that.setData({
            joinCate: 1
        });
        var id = e.detail.id;
        //不是会员
                if (that.data.vipStatus <= 0) {
            //付费会员才可以购买
            if (e.detail.onlyvip == 1) {
                wx.showModal({
                    title: "提示",
                    content: "该商品仅限会员购买，请先成为会员",
                    confirmText: "去升级",
                    success(res) {
                        if (res.confirm) {
                            wx.redirectTo({
                                url: "/memberVip/pages/memberAuthor/memberAuthor"
                            });
                            return;
                        } else {
                            return;
                        }
                    }
                });
                return;
            }
        }
        if (!e.currentTarget.dataset.id) {
            e = {
                currentTarget: {
                    dataset: {
                        id: e.detail.id,
                        single: e.detail.single,
                        minimumnum: e.detail.minimumnum,
                        stepnum: e.detail.stepnum
                    }
                }
            };
        }
        that.join_cart_current(e);
    },
    //加入购物车 此处商品详情接口需要跳转，并且增加加入中的提示
    join_cart_current(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        let single = e.currentTarget.dataset.single;
        var params = {
            id: id
        };
        common.request({
            endpoint: "product/shopping-push",
            method: "post",
            data: params,
            success: res => {
                let details = res.extra;
                this.setData({
                    commission_show: details.commission_show
                });
                details.sku_attribute = details.sku_attribute.map(item => {
                    item.attribute_value = this.selectSingleSku(item.attribute_value);
                    return item;
                });
                let sku_attribute = details.sku_attribute;
                let sku = sku_attribute.reduce((s, v) => {
                    s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                    return s;
                }, "");
                let sku_info = this.getProductBySku(details.sku, sku);
                // let cart_count = wx.getStorageSync("cart_count")
                                if (single == 1) {
                    that.setData({
                        minimum_num: e.currentTarget.dataset.minimumnum,
                        step_num: e.currentTarget.dataset.stepnum
                    });
                    that.join_cart_current_ch(details, e);
                } else {
                    that.setData({
                        details: details,
                        sku: sku,
                        alert: 1,
                        product_id: id,
                        sku_info: sku_info,
                        proId: id,
                        buy_count: 1,
                        spec_fund: details.spec_fund,
                        is_vip: sku_info.is_vip,
                        is_mem_level: sku_info.is_mem_level,
                        vip_price: Number(sku_info.vip_price) > Number(sku_info.mem_level_price) ? sku_info.mem_level_price : sku_info.vip_price
                    });
                }
            }
        });
    },
    //单规格商品购买
    join_cart_current_ch: function(details, e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        let single = e.currentTarget.dataset.single;
        details.sku_attribute = details.sku_attribute.map(item => {
            item.attribute_value = this.selectSingleSku(item.attribute_value);
            return item;
        });
        let sku_attribute = details.sku_attribute;
        let sku = sku_attribute.reduce((s, v) => {
            s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
            return s;
        }, "");
        let sku_info = this.getProductBySku(details.sku, sku);
        if (sku_info.stock_number >= 1) {
            that.cartRequest(sku_info.item_id, "add", id, 1);
        } else {
            wx.showToast({
                title: "库存不足",
                icon: "none"
            });
        }
    },
    cartRequest(sku, type, id, single) {
        let that = this;
        let num = 0;
        if (single == 1) {
            var addC = that.data.joinCate == 1 ? parseInt(that.data.minimum_num) : parseInt(that.data.step_num);
            num = type == "add" ? addC : -addC;
        } else {
            num = that.data.buy_count;
        }
        let goods = that.data.goods;
        let i = goods.findIndex(item => item.id == id);
        if (type != "add") {
            if (goods[i].cart_num <= parseInt(that.data.minimum_num)) {
                num = -goods[i].cart_num;
            }
        }
        common.request({
            endpoint: "Order/cart/add",
            method: "post",
            data: {
                leader_id: that.data.myleaderinfo.leader_id != -1 ? that.data.myleaderinfo.leader_id : 0,
                sku_id: sku,
                business_id: 0,
                num: num,
                flag: 0,
                type: 0
            },
            success: res => {
                if (single == 1) {
                    if (type == "add") {
                        goods[i].cart_num += num;
                    } else {
                        goods[i].cart_num += num;
                    }
                } else {
                    goods[i].cart_num += that.data.buy_count;
                }
                if (goods[i].cart_num < 0) {
                    goods[i].cart_num = 0;
                }
                that.setData({
                    goods: goods,
                    alert: 0
                });
                that.getBase();
                if (that.data.subscribeMessage) {
                    wx.requestSubscribeMessage({
                        tmplIds: that.data.tmplIds,
                        success(res) {},
                        fail(err) {
                            console.log(err);
                        },
                        complete() {}
                    });
                }
            },
            fail: err => {
                wx.showModal({
                    title: "提示",
                    content: err.message
                });
            }
        });
    },
    /**
   * 添加 sku 属性
   */
    addSkuAttribute: function(e) {
        let key_id = parseInt(e.currentTarget.dataset.key_id);
        let value_id = parseInt(e.currentTarget.dataset.value_id);
        let a_key_index = parseInt(e.currentTarget.dataset.a_key_index);
        let a_value_index = parseInt(e.currentTarget.dataset.a_value_index);
        let sku = this.data.sku;
        sku = this.reBlanceSku(sku, key_id, value_id);
        let attribute = this.data.details.sku_attribute;
        attribute = this.selectSku(attribute, a_key_index, a_value_index);
        let sku_info = this.getProductBySku(this.data.details.sku, sku);
        this.setData({
            sku: sku,
            ["details.sku_attribute"]: attribute,
            sku_info: sku_info
        });
    },
    /**
   * 重平衡 sku
   * key_id: integer
   */
    reBlanceSku: function(sku, key_id, value_id) {
        let sku_lib = sku != "" ? this.splitSku(sku) : [];
        sku_lib = this.addSku(sku_lib, {
            key_id: key_id,
            value_id: value_id
        });
        sku_lib = this.sortSku(sku_lib);
        return this.buildSku(sku_lib);
    },
    /**
   * 重建 sku
   */
    buildSku: function(sku_lib) {
        return sku_lib.map(item => {
            return item.key_id + "," + item.value_id;
        }).join("|");
    },
    /**
   * 对选择的 sku 属性进行排序
   */
    sortSku: function(sku_lib) {
        return sku_lib.sort((pre, next) => {
            if (pre.key_id > next.key_id) {
                return 1;
            } else if (pre.key_id < next.key_id) {
                return -1;
            } else {
                return 0;
            }
        });
    },
    /**
   * 分割现有 sku 成对象数组
   */
    splitSku: function(sku) {
        return sku.split("|").map(sku_tmp => {
            let [key, value] = sku_tmp.split(",");
            const t = {};
            t.key_id = parseInt(key);
            t.value_id = parseInt(value);
            return t;
        });
    },
    /**
   * 添加一个 sku
   */
    addSku: function(sku_lib, sku) {
        let t = sku_lib.filter(item => {
            if (item.key_id === sku.key_id) {
                return false;
            }
            return true;
        });
        t.push(sku);
        return t;
    },
    /**
   * 选择 sku
   */
    selectSku: function(attribues, a_index, v_index = 0) {
        if (attribues[a_index]) {
            let values = attribues[a_index].attribute_value;
            values = values.map(item => {
                item.selected = false;
                return item;
            });
            values[v_index].selected = true;
            attribues[a_index].attribute_value = values;
        }
        return attribues;
    },
    /**
   * 选择单个 sku 属性
   */
    selectSingleSku: function(attribute_value, v_index = 0) {
        attribute_value.map(item => {
            item.selected = false;
            return item;
        });
        attribute_value[v_index].selected = true;
        return attribute_value;
    },
    //加入成功后，更新购物车数量
    save_count: function(e) {
        var that = this;
        //判断是否是新人商品
                if (that.data.addShoppingCar) {
            //非新人商品
            this.setData({
                buy_count: parseInt(e.detail.value)
            });
        } else {
            if (that.data.newUserBuyLimit != 0) {
                if (parseInt(e.detail.value > that.data.newUserBuyLimit)) {
                    //判断数值大小有没有超过购买上限
                    //超过上限，设置为上限值
                    that.setData({
                        buy_count: that.data.newUserBuyLimit
                    });
                } else {
                    that.setData({
                        buy_count: parseInt(e.detail.value)
                    });
                }
            } else {
                that.setData({
                    buy_count: parseInt(e.detail.value)
                });
            }
        }
    },
    blur: function(e) {
        let that = this;
        let count = e.detail.value;
        if (count <= 0) {
            count = 1;
        }
        if (count > that.data.sku_info.stock_number) {
            wx.showModal({
                title: that.data.alert_title,
                content: that.data.alert_stock,
                showCancel: false,
                success(res) {
                    that.setData({
                        buy_count: 1
                    });
                }
            });
            return false;
        }
        that.setData({
            buy_count: parseInt(count)
        });
    },
    reduce_count: function() {
        let buy_count = this.data.buy_count;
        if (buy_count > 1) {
            buy_count--;
        }
        this.setData({
            buy_count: buy_count
        });
    },
    add_count: function(e) {
        let that = this;
        if (that.data.buy_count >= that.data.sku_info.stock_number) {
            wx.showModal({
                title: that.data.alert_title,
                content: that.data.alert_stock,
                showCancel: false
            });
            return false;
        }
        that.add_count_ch(e);
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {},
                complete() {}
            });
        }
    },
    add_count_ch: function(e) {
        let that = this;
        let restrictions = that.data.addShoppingCar ? e.currentTarget.dataset.restrictions : e.currentTarget.dataset.newlimit;
        let buy_count = this.data.buy_count;
        if (restrictions == 0) {
            buy_count++;
        } else {
            if (buy_count >= restrictions) {
                wx.showModal({
                    title: that.data.alert_title,
                    content: "本商品限购" + restrictions + "份"
                });
                buy_count = restrictions;
            } else {
                buy_count++;
            }
        }
        this.setData({
            buy_count: buy_count
        });
    },
    /**
   * 根据 sku 获取物品
   */
    getProductBySku: function(sku_products, sku) {
        return sku_products[sku];
    },
    buy: function(e) {
        var that = this;
        //不是会员
                if (that.data.vipStatus <= 0) {
            if (that.data.only_vip == 1) {
                wx.showModal({
                    title: "提示",
                    content: "该商品仅限会员购买，请先成为会员",
                    confirmText: "去升级",
                    success(res) {
                        if (res.confirm) {
                            wx.redirectTo({
                                url: "/memberVip/pages/memberAuthor/memberAuthor"
                            });
                            return;
                        } else {
                            return;
                        }
                    }
                });
                return;
            }
        }
        $author({
            success() {
                var alert = that.data.alert;
                var details = that.data.details;
                var sku_info = that.data.sku_info;
                var buy_count = that.data.buy_count;
                var id = that.data.goodsId;
                var sku_id = sku_info.item_id;
                let sku_item = sku_info.item_id + "," + buy_count + "," + sku_info.credit_sent + "," + details.only_express;
                var price = "";
                if (e.currentTarget.dataset.price) {
                    price = e.currentTarget.dataset.price;
                }
                if (sku_info.stock_number >= buy_count) {
                    wx.navigateTo({
                        url: "/newPlace_order/pages/newPlace_order/newPlace_order?sku_item=" + sku_item + "&status=" + 0 + "&newuserprice=" + price
                    });
                    that.setData({
                        alert: 0,
                        addShoppingCar: true,
                        newUserProductPrice: ""
                    });
                } else {
                    wx.showToast({
                        title: "库存不足",
                        icon: "none"
                    });
                    that.setData({
                        alert: 0
                    });
                }
            }
        });
    },
    join_goods: function(e) {
        let that = this;
        //不是会员
                if (that.data.vipStatus <= 0) {
            if (that.data.only_vip == 1) {
                wx.showModal({
                    title: "提示",
                    content: "该商品仅限会员购买，请先成为会员",
                    confirmText: "去升级",
                    success(res) {
                        if (res.confirm) {
                            wx.redirectTo({
                                url: "/memberVip/pages/memberAuthor/memberAuthor"
                            });
                            return;
                        } else {
                            return;
                        }
                    }
                });
                return;
            }
        }
        that.cartRequest(that.data.sku_info.item_id, "add", that.data.details.product_id, 2);
        // that.join_goods_ch();
        // if (that.data.subscribeMessage) {
        //   wx.requestSubscribeMessage({
        //     tmplIds: that.data.tmplIds,
        //     success(res) {
        //     },
        //     fail(err) {
        //     },
        //     complete() { }
        //   })
        // }
        },
    join_goods_ch: function() {
        var that = this;
        var alert = that.data.alert;
        var cart_count = wx.getStorageSync("cart_count") || 0;
        var details = that.data.details;
        var sku_info = that.data.sku_info;
        var buy_count = that.data.buy_count;
        var id = that.data.product_id;
        cart_count = Number(cart_count) + Number(buy_count);
        var cart = wx.getStorageSync("cart") || [];
        if (cart_count <= 99999) {
            if (sku_info.stock_number >= buy_count) {
                if (cart == "") {
                    let goods = {
                        id: sku_info.item_id,
                        product_id: id,
                        img: details.icon_img,
                        title: details.name,
                        varieties: sku_info.title,
                        price: sku_info.price,
                        o_price: sku_info.o_price,
                        count: buy_count,
                        stock_number: sku_info.stock_number,
                        select: 1,
                        proID: id,
                        status: 1,
                        credit_sent: sku_info.credit_sent || 0,
                        spec_fund: details.spec_fund,
                        is_vip: sku_info.is_vip,
                        is_mem_level: sku_info.is_mem_level,
                        vip_price: Number(sku_info.vip_price) > Number(sku_info.mem_level_price) ? sku_info.mem_level_price : sku_info.vip_price
                    };
                    wx.showToast({
                        title: that.data.alert_success,
                        icon: "none",
                        success: res => {
                            wx.setStorage({
                                key: "cart_count",
                                data: cart_count
                            });
                            this.setData({
                                cart_count: cart_count,
                                pro_share: false
                            });
                            common.changeIconNum(cart_count, 2);
                            var cart = wx.getStorageSync("cart") || that.data.cart;
                            if (!cart) {
                                cart = [];
                            }
                            cart.push(goods);
                            wx.setStorage({
                                key: "cart",
                                data: cart
                            });
                            setTimeout(() => {
                                let newShoppingCart = shoppingCar.getInfo();
                                var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                                that.setData({
                                    buy_count: 1,
                                    alert: 0,
                                    goods: newPro
                                });
                            }, 500);
                        }
                    });
                } else {
                    var total = 0;
                    var index = 0;
                    for (var i = 0; i < cart.length; i++) {
                        if (sku_info.item_id != cart[i]["id"]) {
                            total++;
                        } else {
                            index = i;
                            break;
                        }
                    }
                    if (total == cart.length) {
                        let goods = {
                            id: sku_info.item_id,
                            product_id: id,
                            img: details.icon_img,
                            title: details.name,
                            varieties: sku_info.title,
                            price: sku_info.price,
                            o_price: sku_info.o_price,
                            count: buy_count,
                            stock_number: sku_info.stock_number,
                            select: 1,
                            proID: id,
                            status: 1,
                            credit_sent: sku_info.credit_sent || 0,
                            spec_fund: details.spec_fund,
                            is_vip: sku_info.is_vip,
                            is_mem_level: sku_info.is_mem_level,
                            vip_price: Number(sku_info.vip_price) > Number(sku_info.mem_level_price) ? sku_info.mem_level_price : sku_info.vip_price
                        };
                        wx.showToast({
                            title: that.data.alert_success,
                            icon: "none",
                            success: res => {
                                wx.setStorage({
                                    key: "cart_count",
                                    data: cart_count
                                });
                                this.setData({
                                    cart_count: cart_count
                                });
                                common.changeIconNum(cart_count, 2);
                                var cart = wx.getStorageSync("cart") || that.data.cart;
                                cart.push(goods);
                                wx.setStorage({
                                    key: "cart",
                                    data: cart
                                });
                                setTimeout(() => {
                                    let newShoppingCart = shoppingCar.getInfo();
                                    var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                                    that.setData({
                                        buy_count: 1,
                                        alert: 0,
                                        goods: newPro
                                    });
                                }, 500);
                            }
                        });
                    } else {
                        cart[index]["count"] = cart[index]["count"] + buy_count;
                        wx.showToast({
                            title: that.data.alert_success,
                            icon: "none",
                            success: res => {
                                wx.setStorage({
                                    key: "cart_count",
                                    data: cart_count
                                });
                                this.setData({
                                    cart_count: cart_count,
                                    pro_share: false
                                });
                                common.changeIconNum(cart_count, 2);
                                wx.setStorage({
                                    key: "cart",
                                    data: cart
                                });
                                setTimeout(() => {
                                    let newShoppingCart = shoppingCar.getInfo();
                                    var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                                    that.setData({
                                        buy_count: 1,
                                        alert: 0,
                                        goods: newPro
                                    });
                                }, 500);
                            }
                        });
                    }
                }
            } else {
                wx.showToast({
                    title: that.data.alert_error,
                    icon: "none"
                });
            }
        } else {
            wx.showToast({
                title: that.data.alert_shopcart,
                icon: "none"
            });
        }
    },
    //提示框
    toastControl(content, time) {
        var that = this;
        that.setData({
            toastContent: content,
            toastHide: false
        });
        //显示提示框
                setTimeout(() => {
            that.setData({
                toastHide: true
            });
        }, !time ? 3e3 : time);
        //定时隐藏提示框,默认3秒后隐藏
        },
    //购物车减
    reduceCount(e) {
        let that = this;
        that.setData({
            joinCate: 2
        });
        //不是会员
                if (that.data.vipStatus <= 0) {
            if (e.detail.onlyvip == 1) {
                wx.showModal({
                    title: "提示",
                    content: "该商品仅限会员购买，请先成为会员",
                    confirmText: "去升级",
                    success(res) {
                        if (res.confirm) {
                            wx.redirectTo({
                                url: "/memberVip/pages/memberAuthor/memberAuthor"
                            });
                            return;
                        } else {
                            return;
                        }
                    }
                });
                return;
            }
        }
        console.log(e);
        var id = e.detail.id;
        let single = e.detail.single;
        if (e.detail.single == 1) {
            var params = {
                id: id
            };
            common.request({
                // endpoint: 'product/product_info',
                endpoint: "product/shopping-push",
                method: "post",
                data: params,
                success: res => {
                    let details = res.extra;
                    this.setData({
                        commission_show: details.commission_show
                    });
                    details.sku_attribute = details.sku_attribute.map(item => {
                        item.attribute_value = this.selectSingleSku(item.attribute_value);
                        return item;
                    });
                    let sku_attribute = details.sku_attribute;
                    let sku = sku_attribute.reduce((s, v) => {
                        s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                        return s;
                    }, "");
                    let sku_info = this.getProductBySku(details.sku, sku);
                    if (single == 1) {
                        that.setData({
                            minimum_num: e.detail.minimumnum,
                            step_num: e.detail.stepnum
                        });
                        that.cartRequest(sku_info.item_id, "reduce", id, 1);
                    } else {
                        that.setData({
                            details: details,
                            sku: sku,
                            alert: 1,
                            product_id: id,
                            sku_info: sku_info,
                            proId: id,
                            buy_count: 1,
                            spec_fund: details.spec_fund,
                            is_vip: sku_info.is_vip,
                            is_mem_level: sku_info.is_mem_level,
                            vip_price: Number(sku_info.vip_price) > Number(sku_info.mem_level_price) ? sku_info.mem_level_price : sku_info.vip_price
                        });
                    }
                }
            });
        } else {
            wx.showToast({
                title: that.data.alert_mes1,
                icon: "none"
            });
        }
        // if (e.detail.single == 1) {
        //   var newShoppingCart = shoppingCar.reducePro([e.detail.id]);
        //   var newPro = that.changeProInfo(that.data.goods, newShoppingCart); //改变购物车上标数量
        //   that.setData({
        //     cart_count: newShoppingCart.cart_count,
        //     goods: newPro
        //   })
        //   common.changeIconNum(newShoppingCart.cart_count, 2)
        // } else {
        //   wx.showToast({
        //     title: that.data.alert_mes1,
        //     icon: "none"
        //   })
        // }
        },
    //加
    addCount(e) {
        let that = this;
        that.setData({
            joinCate: 2
        });
        //不是会员
                if (that.data.vipStatus <= 0) {
            if (e.detail.onlyvip == 1) {
                wx.showModal({
                    title: "提示",
                    content: "该商品仅限会员购买，请先成为会员",
                    confirmText: "去升级",
                    success(res) {
                        if (res.confirm) {
                            wx.redirectTo({
                                url: "/memberVip/pages/memberAuthor/memberAuthor"
                            });
                            return;
                        } else {
                            return;
                        }
                    }
                });
                return;
            }
        }
        if (e.detail.item.buyCount >= e.detail.item.all_stock_num) {
            wx.showModal({
                title: that.data.alert_title,
                content: that.data.alert_stock,
                showCancel: false
            });
            return false;
        }
        that.addCount_ch(e);
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {},
                complete() {}
            });
        }
    },
    addCount_ch: function(e) {
        e = {
            currentTarget: {
                dataset: {
                    id: e.detail.id,
                    single: e.detail.single,
                    minimumnum: e.detail.minimumnum,
                    stepnum: e.detail.stepnum
                }
            }
        };
        this.join_cart_current(e);
    },
    /**
   * 商品信息修改
   */
    changeProInfo(proInfo, cartInfoParamter) {
        var cartInfo = cartInfoParamter ? cartInfoParamter.statisticsArry : shoppingCar.getInfo().statisticsArry;
        if (proInfo.length > 0) {
            proInfo.forEach((item, index) => {
                if (cartInfo.length > 0) {
                    for (var i = 0; i < cartInfo.length; i++) {
                        if (item.id == cartInfo[i].product_id) {
                            item.buyCount = cartInfo[i].count;
                            break;
                        } else {
                            item.buyCount = 0;
                        }
                    }
                } else {
                    item.buyCount = 0;
                }
            });
        }
        return proInfo;
    },
    goToOtherFunction(e) {
        wx.navigateTo({
            url: "/localLifePackage/pages/pro_detail/pro_detail"
        });
    }
});